package com.fare.taluo.core.domain.crawl.adapter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.conf.PropertyUtils;
import com.fare.taluo.core.domain.crawl.CrawlCSAirLineModel;
import com.fare.taluo.core.domain.crawl.CrawlPropertiesLoader;
import com.fare.taluo.core.domain.crawl.CrawlTaskModel;
import com.foreveross.proxyip.IProxyIpProvider;
import com.foreveross.proxyip.ProxyIpModel;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ProxyConfig;
import com.gargoylesoftware.htmlunit.WebClient;


/**
 * 适配器的抽象类
 * 职责：抽象公共方法
 * @author Deng
 *
 */
public abstract class AbstractAdapter implements IChannelAdapter{
	
	protected Log logger= LogFactory.getLog(getClass());
	private int timeOut=20000;
	protected CrawlTaskModel taskModel;
	protected CrawlCSAirLineModel portModel;
	protected ProxyIpModel proxyIp;
	
	protected byte[] writeByte(InputStream is) throws IOException{
		int count = 0;
		if(is == null) return new byte[0];
		ByteArrayOutputStream	os = null;
		byte[] data = null;
		try{
			 os = new ByteArrayOutputStream();
			 data = new byte[1024];
				while ((count = is.read(data)) > 0) {
					os.write(data, 0, count);
				}
			return os.toByteArray();
		}finally{
			os = null;
			data = null;
		}
	}
	
	public AbstractAdapter(CrawlTaskModel taskModel){
		this.taskModel = taskModel;
		//如果使用代理IP
		boolean useProxy = PropertyUtils.getBooleanProperty("crawl.use.proxyip", CrawlPropertiesLoader.CONFIG_FILE);
		if(useProxy){
			IProxyIpProvider ipProvider = InstanceFactory.getInstance(IProxyIpProvider.class);
			proxyIp = ipProvider.provideProxyIp();
		}
	}
	public AbstractAdapter(CrawlCSAirLineModel portModel){
		this.portModel = portModel;
		//如果使用代理IP
		boolean useProxy = PropertyUtils.getBooleanProperty("crawl.use.proxyip", CrawlPropertiesLoader.CONFIG_FILE);
		if(useProxy){
			IProxyIpProvider ipProvider = InstanceFactory.getInstance(IProxyIpProvider.class);
			proxyIp = ipProvider.provideProxyIp();
		}
	}
	
	
	protected HttpClient getHttpClient(){
		HttpClient httpClient = new DefaultHttpClient();
		if(proxyIp != null){
			HttpHost proxyHost = new HttpHost(proxyIp.getIp(), proxyIp.getPort(), "http");
			httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
		}
		//模拟浏览器，解决一些服务器程序只允许浏览器访问的问题
		httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
		httpClient.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
		httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,15000);
		httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		return httpClient;
	}

	
	
	/**
	 * 根据抓取策略初始化webclient对象
	 * @return WebClient
	 */
	
	protected WebClient getWebClient(){
		WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);//FIREFOX_10  FIREFOX_3_6
		webClient.setTimeout(this.timeOut);
		//webClient.getOptions().setCssEnabled(false);
		if(proxyIp != null){
			webClient.getOptions().setProxyConfig(new ProxyConfig(proxyIp.getIp(), proxyIp.getPort()));
		}
		return webClient;
	}
	/**
	 * 统一多个getJSONObject获取值方法
	 * jsonKeyStr="oneway_data,priceInfo,keyName"
	 * key = lowpr
	 * String lowerPrice = jsonObject.getJSONObject("oneway_data").getJSONObject("priceInfo").getJSONObject(keyName).get("lowpr").toString();
	 */
	public String getJSONObject(JSONObject jsonObject, String jsonKeyStr, String key) {
		JSONObject tmpJsonObject = jsonObject;
		if (!StringUtils.isEmpty(jsonKeyStr) && !StringUtils.isEmpty(key)) {
			String[] jsonKeys = jsonKeyStr.split(",");
			//遍历
			for (String jsonKey : jsonKeys) {
				tmpJsonObject = tmpJsonObject.getJSONObject(jsonKey);
				//if (tmpJsonObject != null)break;
			}
			if(tmpJsonObject!=null){
				Object obj = tmpJsonObject.get(key);
				if(obj!=null)return obj.toString();
			}
		}
		//logger.error("源网页原始数据为空");
		//throw new SourceWebPageNullException("源网页原始数据为空");
		return  null;
	}
	

}
